package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"yuekaoHouse/api/pkg"

	"yuekaoHouse/api/internal/svc"
	"yuekaoHouse/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QiNiYunLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQiNiYunLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QiNiYunLogic {
	return &QiNiYunLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QiNiYunLogic) QiNiYun(r *http.Request) (resp *types.RegMsgResponse, err error) {
	// todo: 七牛云文件上传

	file, image, err := r.FormFile("images")
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "文件获取失败",
			Data: nil,
		}, err
	}
	//关闭文件
	defer file.Close()

	//获取文件名后缀
	ext := filepath.Ext(image.Filename)
	//判断文件格式
	if !(ext == ".png" || ext == ".jpg") {
		return &types.RegMsgResponse{
			Cre:  -2,
			Mag:  "文件格式错误",
			Data: nil,
		}, err
	}

	if image.Size > 1024*1024*2 {
		return &types.RegMsgResponse{
			Cre:  -3,
			Mag:  "文件大小不能超过2M",
			Data: nil,
		}, err
	}

	err = pkg.QiNiuYun(file)
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "文件上传失败",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Cre:  0,
		Mag:  "文件上传成功",
		Data: nil,
	}, err
}
